<template>
  <div class="pollution-outlet-detail">
    <h3 class="outlet-title">{{ outletName }}排污口</h3>
    <!-- 标签页容器：添加固定宽高的外层容器，避免切换时样式丢失 -->
    <div class="tabs-wrapper" style="width: 100%; height: auto">
      <el-tabs v-model="activeTab" type="card" @tab-click="handleTabChange">
        <!-- 基本信息页：不变 -->
        <el-tab-pane label="基本信息" name="basic">
          <div class="tab-content basic-info">
            <ul class="info-list">
              <li>
                <span class="label">排污口编码：</span
                >{{ outletInfo.outfallcode }}
              </li>
              <li>
                <span class="label">排污口分类：</span
                >{{ outletInfo.outfallfirstclassifycode }}
              </li>
              <li><span class="label">区划：</span>{{ outletInfo.county }}</li>
              <li>
                <span class="label">受纳水体：</span
                >{{ outletInfo.receivingWater }}
              </li>
              <li>
                <span class="label">经度：</span>{{ outletInfo.longitude }}
              </li>
              <li>
                <span class="label">纬度：</span>{{ outletInfo.latitude }}
              </li>
              <li><span class="label">地址：</span>{{ outletInfo.address }}</li>
              <li>
                <span class="label">管理单位：</span>{{ outletInfo.setunits }}
              </li>
            </ul>
            <div class="responsibility-table">
              <h4>责任主体</h4>
              <el-table :data="responsibilityList" border style="width: 100%">
                <el-table-column
                  prop="majorentprise"
                  label="名称"
                ></el-table-column>
                <el-table-column
                  prop="industrytypename"
                  label="行业类别"
                ></el-table-column>
                <el-table-column
                  prop="regioncode"
                  label="行政区划"
                ></el-table-column>
                <el-table-column
                  prop="address"
                  label="详细地址"
                ></el-table-column>
                <el-table-column
                  prop="entpriselink"
                  label="联系人"
                ></el-table-column>
                <el-table-column
                  prop="entprisetel"
                  label="联系方式"
                ></el-table-column>
                <el-table-column
                  prop="dischargepermit"
                  label="排放许可"
                ></el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>

        <!-- 关系拓扑图：外层容器强制宽高 -->
        <el-tab-pane label="关系拓扑图" name="topology">
          <div class="tab-content topology-chart">
            <div
              ref="topologyChart"
              class="chart-container"
              style="width: 100% !important; height: 300px !important"
            ></div>
          </div>
        </el-tab-pane>

        <!-- 关联分析：两个图表容器都加强制宽高 -->
        <el-tab-pane label="关联分析" name="analysis">
          <div class="tab-content correlation-analysis">
            <h4>排污口与污染源关联分析</h4>
            <el-form inline :model="analysisForm" class="query-form">
              <el-form-item label="时间">
                <el-date-picker
                  v-model="analysisForm.timeRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="排污口污染物">
                <el-select
                  v-model="analysisForm.pollutant"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, index) in wrwlist"
                    :key="index"
                    :label="item.pollutantname"
                    :value="item.pollutantcode"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="seracha">查询</el-button>
              </el-form-item>
            </el-form>
            <div
              ref="sourceChart"
              class="chart-container"
              style="width: 100% !important; height: 300px !important"
            ></div>

            <h4 style="margin-top: 20px">排污口与上下游关联分析</h4>
            <el-form inline :model="analysisForm2" class="query-form">
              <el-form-item label="时间">
                <el-date-picker
                  v-model="analysisForm2.timeRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="排污口污染物">
                <el-select
                  v-model="analysisForm2.pollutant"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, index) in wrwlist"
                    :key="index"
                    :label="item.pollutantname"
                    :value="item.pollutantcode"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="serachb">查询</el-button>
              </el-form-item>
            </el-form>
            <div
              ref="upstreamChart"
              class="chart-container"
              style="width: 100% !important; height: 300px !important"
            ></div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import dayjs from "dayjs";
import {
  getResponsibilityDetail,
  getResponsibilityListByOutfall,
  getPollutionOptions,
  getOutfallPollutionRelation,
  getOutfallUpDownRelation,
  getPollutionByOutfall,
  getSectionByOutfall,
} from "@/api/traceability";

export default {
  name: "PollutionOutletDetail",
  props: {
    outletName: { type: String, default: "" },
    pkid: { type: String, default: "" },
  },
  watch: {
    pkid: {
      handler(val) {
        if (val) {
          this.getBasicInfoItem();
          this.getResponsibilityList();
          // 并行请求拓扑图所需的两个接口
          Promise.all([
            this.getPollutionByOutfall(),
            this.getSectionByOutfall(),
          ]).then(() => {
            // 两个接口都请求完成后，如果当前是拓扑图标签则渲染
            if (this.activeTab === "topology") {
              this.initTopologyChart();
            }
          });
        }
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      activeTab: "basic",
      outletInfo: {},
      responsibilityList: [],
      analysisForm: {
        timeRange: [],
        pollutant: "",
      },
      analysisForm2: {
        timeRange: [],
        pollutant: "",
      },
      wrwlist: [],
      topologyChart: null,
      sourceChart: null,
      upstreamChart: null,
      arra: [], // 污染源数据
      arrb: [], // 断面数据
    };
  },
  created() {
    this.analysisForm.timeRange = [
      dayjs().startOf("month").format("YYYY-MM-DD"),
      dayjs().format("YYYY-MM-DD"),
    ];
    this.analysisForm2.timeRange = [
      dayjs().startOf("month").format("YYYY-MM-DD"),
      dayjs().format("YYYY-MM-DD"),
    ];
  },
  mounted() {
    this.getPollutionOptions();
    window.addEventListener("resize", this.handleWindowResize);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleWindowResize);
    this.topologyChart && this.topologyChart.dispose();
    this.sourceChart && this.sourceChart.dispose();
    this.upstreamChart && this.upstreamChart.dispose();
  },
  methods: {
    // 基本信息
    getBasicInfoItem() {
      getResponsibilityDetail(this.pkid).then((res) => {
        res.code === 200 && (this.outletInfo = res.data);
      });
    },
    // 责任列表
    getResponsibilityList() {
      getResponsibilityListByOutfall(this.pkid).then((res) => {
        res.code === 200 && (this.responsibilityList = res.data);
      });
    },
    // 获取污染物选项
    getPollutionOptions() {
      getPollutionOptions().then((res) => {
        this.wrwlist = res.data || [];
        if (this.wrwlist.length > 0) {
          this.analysisForm.pollutant = this.wrwlist[0].pollutantcode;
          this.analysisForm2.pollutant = this.wrwlist[0].pollutantcode;
        }
      });
    },
    // 关系拓扑图-根据排口获取污染源
    getPollutionByOutfall() {
      return new Promise((resolve) => {
        getPollutionByOutfall(this.pkid)
          .then((res) => {
            this.arra = res.data || [];
            resolve();
          })
          .catch(() => resolve());
      });
    },
    // 关系拓扑图-根据排口获取断面信息
    getSectionByOutfall() {
      return new Promise((resolve) => {
        getSectionByOutfall(this.pkid)
          .then((res) => {
            this.arrb = res.data || [];
            resolve();
          })
          .catch(() => resolve());
      });
    },
    // 标签切换处理
    handleTabChange(tab) {
      const tabName = tab.name;
      setTimeout(() => {
        if (tabName === "topology") {
          // 确保两个接口数据都加载完成后再渲染
          Promise.all([
            this.arra.length > 0
              ? Promise.resolve()
              : this.getPollutionByOutfall(),
            this.arrb.length > 0
              ? Promise.resolve()
              : this.getSectionByOutfall(),
          ]).then(() => {
            this.initTopologyChart();
          });
        } else if (tabName === "analysis") {
          this.seracha();
          this.serachb();
        }
      }, 300);
    },

    // 初始化拓扑图（核心改造）
    initTopologyChart() {
      const chartDom = this.$refs.topologyChart;
      if (!chartDom) return;

      // 销毁旧实例
      this.topologyChart && this.topologyChart.dispose();
      this.topologyChart = echarts.init(chartDom);

      // 1. 动态构建节点数据
      const dataArr = [];
      // 排污口节点（必选）
      dataArr.push({
        name: this.outletName,
        value: [-50, 50], // 固定位置
      });
      // 污染源节点（arra有数据才添加）
      if (this.arra.length > 0) {
        dataArr.push({
          name: "污染源",
          value: [50, 50], // 右侧位置
        });
      }
      // 断面节点（arrb有数据才添加）
      if (this.arrb.length > 0) {
        dataArr.push({
          name: "断面",
          value: [-50, -30], // 下方位置
        });
      }

      // 2. 动态构建连线数据
      const links = [];
      // 排污口 -> 污染源（如果存在）
      if (this.arra.length > 0) {
        links.push({
          source: 0, // 排污口索引
          target: 1, // 污染源索引
        });
      }
      // 排污口 -> 断面（如果存在）
      if (this.arrb.length > 0) {
        const sectionIndex = this.arra.length > 0 ? 2 : 1; // 计算断面索引
        links.push({
          source: 0, // 排污口索引
          target: sectionIndex, // 断面索引
        });
      }

      // 3. 图表配置
      const option = {
        grid: { containLabel: true, top: 30, bottom: 30 },
        xAxis: { min: -120, max: 120, type: "value", show: false },
        yAxis: { min: -120, max: 120, type: "value", show: false },
        series: [
          {
            id: "topology",
            type: "graph",
            layout: "none",
            coordinateSystem: "cartesian2d",
            symbolSize: 70,
            roam: false,
            label: {
              show: true,
              color: "#333333", // 改为深灰色文字，白色背景下清晰可见
              fontSize: 14,
              fontWeight: 600, // 加粗文字，增强可读性
              formatter: (d) => dataArr[d.dataIndex].name,
              distance: 0,
              backgroundColor: "rgba(255,255,255,0.8)", // 文字背景半透明白色，进一步提升对比度
              padding: [4, 8], // 文字内边距，避免贴边
              borderRadius: 4, // 文字背景圆角，更美观
            },
            itemStyle: {
              borderColor: "#e0e0e0", // 浅灰色边框，区分节点与背景
              borderWidth: 2,
              borderRadius: 35, // 圆形节点
              color: (params) => {
                // 调整渐变颜色，更柔和不刺眼
                const colorList = [
                  ["#66b1ff", "#a6cfff"], // 排污口：浅蓝渐变
                  ["#33EBAA", "#79f2c0"], // 污染源：浅绿渐变
                  ["#FF9E4D", "#ffc085"], // 断面：浅橙渐变
                ];
                return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: colorList[params.dataIndex][0] },
                  { offset: 1, color: colorList[params.dataIndex][1] },
                ]);
              },
              shadowBlur: 8,
              shadowColor: "rgba(0, 0, 0, 0.08)", // 弱化阴影，避免干扰
            },
            lineStyle: {
              color: (params) => {
                const lineColorList = ["#409EFF", "#00E599", "#FF7D00"];
                return lineColorList[params.dataIndex];
              },
              width: 3,
              curveness: 0.1,
              opacity: 0.8,
            },
            edgeSymbol: ["none", "arrow"],
            edgeSymbolSize: [0, 10],
            data: dataArr.map((item) => item.value),
            edges: links,
          },
        ],
      };

      this.topologyChart.setOption(option);
      this.topologyChart.resize();
    },

    // 污染源关联分析查询
    seracha() {
      const query = {
        outfallid: this.pkid,
        pollutantcode: this.analysisForm.pollutant,
        startTime: this.analysisForm.timeRange[0] || "",
        endTime: this.analysisForm.timeRange[1] || "",
      };
      getOutfallPollutionRelation(query).then((res) => {
        this.queryPollutionSource(res.data || {});
      });
    },

    // 渲染污染源图表
    queryPollutionSource(data) {
      const chartDom = this.$refs.sourceChart;
      if (!chartDom) return;

      this.sourceChart && this.sourceChart.dispose();
      this.sourceChart = echarts.init(chartDom);
      const option = {
        title: { text: "排污口与污染源关联分析" },
        xAxis: { type: "category", data: data.timelist || [] },
        yAxis: { type: "value", name: "浓度(mg/L)" },
        series: [
          {
            name: this.outletName,
            type: "line",
            data: data.datalist || [],
            smooth: true,
          },
        ],
      };
      this.sourceChart.setOption(option);
    },

    // 上下游关联分析查询
    serachb() {
      const query = {
        outfallid: this.pkid,
        pollutantcode: this.analysisForm2.pollutant,
        startTime: this.analysisForm2.timeRange[0] || "",
        endTime: this.analysisForm2.timeRange[1] || "",
      };
      getOutfallUpDownRelation(query).then((res) => {
        this.queryUpstreamDownstream(res.data || {});
      });
    },

    // 渲染上下游图表
    queryUpstreamDownstream(data) {
      const chartDom = this.$refs.upstreamChart;
      if (!chartDom) return;

      this.upstreamChart && this.upstreamChart.dispose();
      this.upstreamChart = echarts.init(chartDom);
      const option = {
        title: { text: "排污口与上下游关联分析" },
        xAxis: { type: "category", data: data.timelist || [] },
        yAxis: { type: "value", name: "浓度(mg/L)" },
        series: [
          {
            name: "排污口浓度",
            type: "line",
            data: data.datalist || [],
            smooth: true,
          },
          {
            name: "下游断面浓度",
            type: "line",
            data: data.downstreamList || [],
            smooth: true,
          },
        ],
      };
      this.upstreamChart.setOption(option);
    },

    // 窗口缩放处理
    handleWindowResize() {
      setTimeout(() => {
        this.topologyChart && this.topologyChart.resize();
        this.sourceChart && this.sourceChart.resize();
        this.upstreamChart && this.upstreamChart.resize();
      }, 100);
    },
  },
};
</script>

<style scoped>
.pollution-outlet-detail {
  padding: 20px;
  background: #fff;
  width: 100%;
  box-sizing: border-box;
}
.outlet-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 15px;
}
.tabs-wrapper {
  width: 100% !important;
  height: auto;
  box-sizing: border-box;
}
.el-tabs--card > .el-tabs__content {
  width: 100% !important;
  box-sizing: border-box;
}
.el-tabs--card > .el-tabs__header {
  border-bottom: 1px solid #e4e7ed;
  width: 100% !important;
}
.tab-content {
  margin-top: 20px;
  width: 100% !important;
  box-sizing: border-box;
}
.info-list {
  list-style: none;
  padding: 0;
  display: flex;
  flex-wrap: wrap;
}
.info-list li {
  width: 50%;
  margin-bottom: 10px;
  line-height: 24px;
}
.label {
  font-weight: 500;
  margin-right: 5px;
}
.responsibility-table {
  margin-top: 20px;
}
.responsibility-table h4 {
  font-size: 14px;
  margin-bottom: 10px;
}
.chart-container {
  width: 100%;
  height: 300px;
  margin-top: 10px;
  min-width: 300px;
}
.query-form {
  margin-bottom: 10px;
}
</style>
